<route lang="json5">
{
  needLogin: true,
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '文件预览',
  },
}
</route>
<template>
  <view class="document-preview">
    <!-- 顶部导航栏 -->
    <wd-navbar
      title="文件预览"
      left-arrow
      placeholder
      @click-left="handleBack"
      custom-style="background: #fff; border-bottom: none;"
      fixed
      safeAreaInsetTop
    ></wd-navbar>
    <!-- H5端使用iframe预览 -->
    <template v-if="isH5">
      <iframe v-if="previewUrl" :src="previewUrl" class="preview-iframe" frameborder="0"></iframe>
      <view v-else class="error-tip">
        <text>该文件暂不支持预览</text>
        <wd-button type="primary" size="small" @click="downloadFile">下载文件</wd-button>
      </view>
    </template>

    <!-- 非H5端显示提示 -->
    <template v-else>
      <iframe v-if="previewUrl" :src="previewUrl" class="preview-iframe" frameborder="0"></iframe>
      <view v-else class="error-tip">
        <text>该文件暂不支持预览</text>
        <wd-button type="primary" size="small" @click="downloadFile">下载文件</wd-button>
      </view>
      <!-- <view class="preview-container">
          <view class="file-info">
            <image :src="getFileIcon" class="file-icon" />
            <text class="file-name">{{ fileName }}</text>
          </view>
          <wd-button type="primary" block @click="downloadAndOpen">打开文件</wd-button>
        </view> -->
    </template>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getFileIconByPath } from '@/utils/file'
import encode from 'wot-design-uni/components/common/base64'

const fileName = ref('')
const fileUrl = ref('')
const isH5 = ref(false)

// 获取文件图标
const getFileIcon = computed(() => {
  return `/static/images/file/${getFileIconByPath(fileUrl.value)}.png`
})

// 获取预览URL
const previewUrl = computed(() => {
  console.log('fileUrl.value====', fileUrl.value)
  if (!fileUrl.value) return ''

  const ext = fileUrl.value.split('.').pop()?.toLowerCase()

  // Office文件使用微软在线预览
  if (['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(ext)) {
    return `${import.meta.env.VITE_PREVIEW_BASEURL}/onlinePreview?url=${encodeURIComponent(encode(fileUrl.value))}`
  }

  // PDF文件使用PDF.js预览
  if (ext === 'pdf') {
    return `${import.meta.env.VITE_PREVIEW_BASEURL}/onlinePreview?url=${encodeURIComponent(encode(fileUrl.value))}`
  }
  // 视频预览
  if (['mp4'].includes(ext)) {
    return `${import.meta.env.VITE_PREVIEW_BASEURL}/onlinePreview?url=${encodeURIComponent(encode(fileUrl.value))}`
  }
  // 图片预览
  if (['jpg'].includes(ext)) {
    return `${import.meta.env.VITE_PREVIEW_BASEURL}/onlinePreview?url=${encodeURIComponent(encode(fileUrl.value))}`
  }

  return ''
})

// 下载并打开文件
const downloadAndOpen = async () => {
  uni.showLoading({
    title: '正在下载...',
  })

  try {
    const res = await uni.downloadFile({
      url: fileUrl.value,
      success: (downloadRes) => {
        if (downloadRes.statusCode === 200) {
          uni.openDocument({
            filePath: downloadRes.tempFilePath,
            showMenu: true,
            success: () => {
              console.log('打开文档成功')
            },
            fail: () => {
              uni.showToast({
                title: '打开文件失败',
                icon: 'none',
              })
            },
          })
        }
      },
      fail: () => {
        uni.showToast({
          title: '下载失败',
          icon: 'none',
        })
      },
      complete: () => {
        uni.hideLoading()
      },
    })
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '下载失败',
      icon: 'none',
    })
  }
}

// 下载文件
const downloadFile = () => {
  // #ifdef H5
  window.open(fileUrl.value, '_blank')
  // #endif

  // #ifndef H5
  downloadAndOpen()
  // #endif
}

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

onMounted(() => {
  // #ifdef H5
  isH5.value = true
  // #endif

  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.$page?.options

  if (options?.url) {
    fileUrl.value = decodeURIComponent(options.url)
  }
  if (options?.name) {
    fileName.value = decodeURIComponent(options.name)
  }
})
</script>

<style lang="scss" scoped>
.document-preview {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #fff;

  .preview-iframe {
    flex: 1;
    width: 100%;
    height: calc(100vh - 88rpx);
    border: none;
  }

  .preview-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: calc(100vh - 88rpx);
    padding: 32rpx;

    .file-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 48rpx;

      .file-icon {
        width: 120rpx;
        height: 120rpx;
        margin-bottom: 24rpx;
      }

      .file-name {
        max-width: 80%;
        font-size: 32rpx;
        color: #333;
        text-align: center;
        word-break: break-all;
      }
    }
  }

  .error-tip {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: calc(100vh - 88rpx);
    color: #999;

    .wd-button {
      margin-top: 32rpx;
    }
  }
}
</style>
